`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 2021/08/03 21:50:55
// Design Name: 
// Module Name: TwoLevelMultiBankBram
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////


module WeightBuffer
#(parameter ADDR_WIDTH = 32,
  parameter DATA_WIDTH = 32,
  parameter Tn = 4,
  parameter Tm = 8,
  parameter K = 3)
(
input logic clk,
input logic rst,
//多端口read
input logic [ADDR_WIDTH-1:0] rd_addr,
output logic [DATA_WIDTH-1:0] rd_data [0:Tm-1][0:Tn-1],
//单端口write
input logic [31:0] m,
input logic [31:0] n,
input logic [31:0] kk,
input logic [DATA_WIDTH-1:0] wr_data,
input logic we
    );
logic wen [0:Tm-1][0:Tn-1];
logic [DATA_WIDTH-1:0] write_data [0:Tm-1][0:Tn-1];
logic [ADDR_WIDTH-1:0] write_addr [0:Tm-1][0:Tn-1];
//write_addr
genvar i,j;
generate
    for(i=0;i<Tm;i++)
        for(j=0;j<Tn;j++)
        begin
            assign write_addr[i][j]=kk;
            assign write_data[i][j]=wr_data;
        end
endgenerate
//wen
always_comb
if(we)
begin
    for(int i=0;i<Tm;i++)
        for(int j=0;j<Tn;j++)
            wen[i][j]=0;
    wen[m][n]=1;
end
else
begin
    for(int i=0;i<Tm;i++)
        for(int j=0;j<Tn;j++)
            wen[i][j]=0; 
end
//例化
generate
    for(i=0; i<Tm; i++)
    begin
        for(j=0;j<Tn;j++)
            begin: bram_inst
                BlockRAM 
                #(.ADDR_WIDTH(ADDR_WIDTH),
                .DATA_WIDTH(DATA_WIDTH),
                .DEPTH(K*K))
                U (
                .clk(clk),
                .rst(rst),
                //read port
                .rd_addr(rd_addr),
                .rd_data(rd_data[i][j]),
                //write port
                .we(wen[i][j]),
                .wr_addr(write_addr[i][j]),
                .wr_data(write_data[i][j])
                );
            end
    end        
endgenerate
endmodule
